<?php
/**
 *  ==============================================================
 *  Created by PhpStorm.
 *  User: Ice
 *  邮箱: ice@sbing.vip
 *  网址: https://sbing.vip
 *  Date: 2020/7/7 下午5:45
 *  ==============================================================
 */

namespace addons\cloudstore\controller;

use addons\cloudstore\library\aliyun\OSS\OssClient;
use addons\cloudstore\library\aliyun\plugins\Verify;
use addons\cloudstore\library\CloudDriver;
use app\common\model\Attachment;
use think\addons\Controller;
use think\facade\Config;
use think\facade\Filesystem;
use think\facade\Log;

/**
 * 云存储
 *
 */
class Index extends Controller
{

    public function index()
    {
        $this->error("当前插件暂无前台页面");
    }

    public function test()
    {
        echo 'test';
    }

    /**
     * 获取签名
     */
    public function params()
    {
        $driver = $this->request->param('driver');
        if (!in_array($driver, ['qiniu', 'qcloud', 'aliyun'])) {
            $this->success('云存储类型错误');
        }
        $name = $this->request->post('name');
        $md5 = $this->request->post('md5');
        $chunk = $this->request->post('chunk');
        $category = $this->request->post('category');
        $__cfg = get_addon_config('cloudstore');
        $cfg = $__cfg[$__cfg['type']] ?? [];
        $dir = 'uploads/';
        $suffix = strtolower(pathinfo($name, PATHINFO_EXTENSION));
        $suffix = $suffix && preg_match("/^[a-zA-Z0-9]+$/", $suffix) ? $suffix : 'file';
        $notify = addon_url('cloudstore/index/notify', [], false, true);
        switch ($driver) {
            case 'aliyun':
                $params = Filesystem::disk(CloudDriver::class)
                    ->getAdapter()->signatureConfig($dir, $notify,
                        [
                            'category' => $category,
                            'file_origin_name' => $name
                        ]);
                $params = json_decode($params, true);
                $params['OSSAccessKeyId'] = $params['accessid'];
                $params['key'] = $dir . date('Ymd') . '/' . $md5 . '.' . $suffix;
                $params['success_action_status'] = 200;
                break;
            case 'qiniu':
                $params['token'] = Filesystem::disk(CloudDriver::class)
                    ->getAdapter()->getUploadToken(
                        $dir . date('Ymd') . '/' . $md5 . '.' . $suffix
                    );
                $params['key'] = $dir . date('Ymd') . '/' . $md5 . '.' . $suffix;
            //$params = json_decode($params, true);
        }
        $this->success('', null, $params);
    }


    /**
     * 阿里云oss 回调
     */
    public function notify()
    {
        Config::set(['default_return_type' => 'json'], 'app');
        $cfg = get_addon_config('cloudstore');
        $ossCfg = $cfg[$cfg['type']];
        $domain = substr($ossCfg['oss_domain'], -1) !== '/' ? $ossCfg['oss_domain'] . '/' : $ossCfg['oss_domain'];

        if ($cfg['type'] == 'aliyun') {
            $filesystem = Filesystem::disk(CloudDriver::class);
            $filesystem->addPlugin(new Verify());
            list($isOk, $data) = $filesystem->verify();
            if ($isOk == false) {
                Log::error('cloudstore notify' . $data['CallbackFailed']);
                $this->error($data['CallbackFailed']);
                return;
            }
            $url = $domain . $data['filename'];
        } elseif ($cfg['type'] == 'qiniu') {
            $url = $this->request->param('url');
            if (empty($url)) {
                $this->error('error');
            }
            $data = $this->request->post('');
            $data['mimeType'] = $data['type'] ?? '';
            $data['file_origin_name'] = $data['name'] ?? '';
        }
        $attachment = Attachment::where('url', $url)->where('storage', 'cloudstore')->find();
        if (!$attachment) {
            $params = array(
                'category' => $data['category'] ?? '',
                'admin_id' => (int)session('admin.id'),
                'user_id' => (int)cookie('uid'),
                'filesize' => $data['size'] ?? 0,
                'filename' => $data['file_origin_name'] ?? '',
                'imagewidth' => $data['width'] ?? 0,
                'imageheight' => $data['height'] ?? 0,
                'imagetype' => $data['format'] ?? '',
                'imageframes' => 0,
                'mimetype' => $data['mimeType'] ?? '',
                'url' => $url,
                'uploadtime' => time(),
                'storage' => 'cloudstore',
                'sha1' => $data['etag'] ?? '',
            );
            Attachment::create($params);
        }
        $this->success('上传成功', '', ['url' => $url]);
    }
}
